package com.yxxt.admin.rest.fdfs;/**
 * @author zwj
 * @date 2020/9/7
 * @description TODO fastDFS集成接口
 */


import com.yxxt.common.client.fdfsClient;
import com.yxxt.common.msg.ObjectRestResponse;
import com.yxxt.common.util.DateUtils;
import com.yxxt.common.util.StringHelper;
import com.yxxt.common.util.ZipUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zwj
 * @className: FastDFSController
 * @packageName: com.test.controller
 * @description: fastDFS集成
 * @data: 2020/9/7
 **/
@RestController
@RequestMapping("/fdfs")
public class FastDFSController {

    @Autowired
    private fdfsClient fdfsClient;


    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws Exception 不写Get 、POST 的都支持
     */
    @ApiOperation(value = "上传文件", notes = "文件上传")
    @PostMapping("/upload")
    public ObjectRestResponse<Object> upload(MultipartFile file) throws Exception {
        String url = fdfsClient.uploadFile(file);
        Map<String, Object> result = new HashMap<>();
        result.put("url", url);
        result.put("fileName", file.getOriginalFilename());
        return ObjectRestResponse.success(result);
    }

    @ApiOperation(value = "上传文件", notes = "文件上传")
    @PostMapping("/uploadReturnJson")
    public ObjectRestResponse<Object> uploadReturnJson(MultipartFile file) throws Exception {
        String url = fdfsClient.uploadFile(file);
        Map<String, Object> result = new HashMap<>();
        result.put(file.getOriginalFilename(), url);
        return ObjectRestResponse.success(result);
    }

    /**
     * 文件下载
     *
     * @param fileUrl  url
     *                 开头从组名开始
     * @param response
     * @throws Exception
     */

    @GetMapping("/download")
    @ApiOperation(value = "文件下载", notes = "文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileUrl", value = "url 开头从组名开始", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", paramType = "query")
    })
    public void download(String fileUrl, String fileName, HttpServletResponse response) throws Exception {
        //String fileName = fileUrl.substring(0, fileUrl.lastIndexOf("."));
        byte[] data = fdfsClient.download(fileUrl);
        if (StringUtils.isEmpty(fileName)) {
            fileName = fileUrl;
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 写出
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
    }

    @GetMapping("/downloadMultiFile")
    @ApiOperation(value = "文件下载", notes = "如果是多文件，以,分割fileUrl")
    @ApiImplicitParam(name = "downloadMultiFile", value = "url 开头从组名开始", dataType = "String", paramType = "query")
    public void downloadMultiFile(String fileUrl, HttpServletResponse response) throws Exception {
        String[] paths = fileUrl.split(",");
        if (paths.length == 1) {
            byte[] data = fdfsClient.download(fileUrl);
            String fileName = fileUrl.substring(0, fileUrl.lastIndexOf("."));

            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileUrl, "UTF-8"));
            // 写出
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.write(data, outputStream);

        } else {
            // 多文件打zip包下载
            Map<String, byte[]> fileMap = new HashMap<>();
            for (int i = 0; i < paths.length; i++) {

                byte[] bt = fdfsClient.download(paths[i]);

                fileMap.put(StringHelper.subFileName(URLEncoder.encode(paths[i], "UTF-8")), bt);
            }
            byte[] bytes = ZipUtils.compress(fileMap);
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + DateUtils.getReqLongDate() + ".zip");
            // 写出
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.write(bytes, outputStream);
        }

    }
}
